////////////////////////////////////////
// EECE494 COMPUTER GRAPHICS
// Spring term 2011
// Assignment 1 Model Rendering
// (Tim) Wei-Ting Liu
// #29144052
////////////////////////////////////////

#include "loadModel.h"

using namespace std;

// Reads and parses lines
loadModel::loadModel(string target){
	ifstream inFile(target, ios::binary);
	if(inFile.is_open()){
		while(inFile.good()){
			string line;
			getline(inFile, line);
			vector<string> subString;
			string buffer;
			stringstream sStream(line);

			while(sStream >> buffer){
				subString.push_back(buffer);
			}
			if(subString.size() != 0){
				string tag = subString[0].substr(0,1);
				string tmpStr;

				switch(tag[0]){
				case 'b':
				case 'B':
					// Building name
					for(int i=1; i<subString.size(); i++)
						buildingName = buildingName + subString[i] + " ";
					break;
				case 'i':
				case 'I':
					// Texture file name
					for(int i=1; i<subString.size(); i++)
						tmpStr = tmpStr + subString[i] + " ";
					texture.push_back(tmpStr);
					break;
				case 'v':
				case 'V':
					// Model vertices
					for(int i=1; i<subString.size(); i++)
						vertex.push_back(atof(subString[i].c_str()));
					break;
				case 'n':
				case 'N':
					// Model normals
					for(int i=1; i<subString.size(); i++)
						normal.push_back(atof(subString[i].c_str()));
					break;
				case 't':
				case 'T':
					// Model triangles
					triangleSet.push_back(loadTriangle(subString));
					break;
				}
			}
		}
		inFile.close();
	}else{
		cout << "Unable to open file " << target << endl;
	}
}

string loadModel::getBuildingName(){ return buildingName; }
vector<string> loadModel::getTexture(){ return texture; }
vector<float> loadModel::getVertex(){ return vertex; }
vector<float> loadModel::getNormal(){ return normal; }
vector<triangle> loadModel::getTriangle(){ return triangleSet; }

loadModel::~loadModel(){}

// Triangles that make up the scene
triangle loadTriangle(vector<string> str){
	triangle tri;
	for(int i=1; i<str.size(); i++){
		if(i>=1 && i<=3)
			tri.vertex.push_back(atoi(str[i].c_str()));
		if(i==4)
			tri.normal = atoi(str[i].c_str());
		if(i==5)
			tri.texture = atoi(str[i].c_str());
		if(i>5)
			tri.textureCoordinate.push_back(atof(str[i].c_str()));
	}
	return tri;
}